<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import defaultProduct from '../assets/logo.jpg'

const orders = ref([])
const loading = ref(false)
const errorMessage = ref('')
const BASE_URL = 'http://localhost:3001'

// 订单状态映射
const ORDER_STATUS = {
    'pending': { text: '待付款', color: '#faad14' },
    'confirmed': { text: '待发货', color: '#1890ff' },
    'shipped': { text: '已发货', color: '#52c41a' },
    'delivered': { text: '已完成', color: '#52c41a' },
    'cancelled': { text: '已取消', color: '#ff4d4f' }
}

// 获取状态文本
const getStatusText = (status) => {
    return ORDER_STATUS[status]?.text || status
}

// 添加搜索和筛选状态
const searchQuery = ref('')
const statusFilter = ref('all')
const timeFilter = ref('all')

// 状态选项
const statusOptions = [
  { value: 'all', label: '所有状态' },
  { value: 'pending', label: '待付款' },
  { value: 'confirmed', label: '待发货' },
  { value: 'shipped', label: '已发货' },
  { value: 'delivered', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
]

// 时间筛选选项
const timeOptions = [
  { value: 'all', label: '全部时间' },
  { value: 'today', label: '今天' },
  { value: 'week', label: '最近7天' },
  { value: 'month', label: '最近30天' }
]

// 计算过滤后的订单列表
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    // 只保留订单号搜索
    const searchTerm = searchQuery.value.trim()
    const matchesSearch = searchTerm === '' || 
      order.order_id.toString().includes(searchTerm)
    
    // 状态筛选
    const matchesStatus = statusFilter.value === 'all' || order.order_status === statusFilter.value
    
    // 时间筛选
    const matchesTime = timeFilter.value === 'all' || isWithinTimeRange(order.created_at, timeFilter.value)
    
    return matchesSearch && matchesStatus && matchesTime
  })
})

// 判断日期是否在指定范围内
const isWithinTimeRange = (dateStr, range) => {
  if (!dateStr) return false
  
  const orderDate = new Date(dateStr)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  switch (range) {
    case 'today':
      return orderDate >= today
    case 'week': {
      const weekAgo = new Date(today)
      weekAgo.setDate(weekAgo.getDate() - 7)
      return orderDate >= weekAgo
    }
    case 'month': {
      const monthAgo = new Date(today)
      monthAgo.setDate(monthAgo.getDate() - 30)
      return orderDate >= monthAgo
    }
    default:
      return true
  }
}

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = 'all'
  timeFilter.value = 'all'
}

// 获取订单列表
const fetchOrders = async () => {
    try {
        loading.value = true
        errorMessage.value = ''
        
        const token = localStorage.getItem('token')
        if (!token) {
            errorMessage.value = '未登录或登录已过期'
            return
        }

        const response = await fetch(`${BASE_URL}/api/admin/orders`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        
        if (!response.ok) {
            throw new Error('获取订单列表失败')
        }

        const data = await response.json()
        // console.log('订单数据:', data)
        
        if (data.code === 200) {
            orders.value = data.data
        } else {
            throw new Error(data.message)
        }
    } catch (error) {
        console.error('获取订单列表失败:', error)
        // errorMessage.value = error.message || '获取订单列表失败'
    } finally {
        loading.value = false
    }
}

// 更新订单状态
const updateOrderStatus = async (orderId, status) => {
    try {
        const token = localStorage.getItem('token')
        const response = await fetch(`${BASE_URL}/api/admin/orders/${orderId}/status`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({ status })
        })

        if (!response.ok) {
            throw new Error('更新订单状态失败')
        }

        const data = await response.json()
        if (data.code === 200) {
            // 更新本地数据
            const order = orders.value.find(o => o.order_id === orderId)
            if (order) {
                order.order_status = status
                order.status_text = ORDER_STATUS[status].text
            }
            alert('更新成功')
        } else {
            throw new Error(data.message || '更新失败')
        }
    } catch (error) {
        console.error('更新订单状态失败:', error)
        alert(error.message || '更新失败')
    }
}

// 删除订单
const deleteOrder = async (orderId) => {
  // 添加确认提示
  if (!confirm('确定要删除这个订单吗？')) {
    return
  }

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      errorMessage.value = '未登录或登录已过期'
      return
    }

    const response = await fetch(`${BASE_URL}/api/admin/orders/${orderId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    const data = await response.json()
    
    if (data.code === 200) {
      // 从本地数据中移除被删除的订单
      orders.value = orders.value.filter(order => order.order_id !== orderId)
      alert('删除成功')
      // 可选：重新获取订单列表
      await fetchOrders()
    } else {
      throw new Error(data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除订单失败:', error)
    alert(error.message || '删除失败')
  }
}

// 格式化价格
const formatPrice = (price) => {
    if (!price) return '¥0.00';
    return `¥${(Number(price) / 100).toFixed(2)}`;
}

// 格式化时间
const formatDate = (date) => {
    if (!date) return '-';
    return new Date(date).toLocaleString();
}

// 处理图片URL
const getImageUrl = (url) => {
    
  if (!url) return defaultProduct
  
  try {
    // 处理字符串格式的图片路径
    const images = typeof url === 'string' ? JSON.parse(url) : url
    
    // 如果是数组且有元素，使用第一个图片
    if (Array.isArray(images) && images.length > 0) {
      // 移除字符串两端的引号和中括号
      const imagePath = images[0].replace(/[\[\]"]/g, '')
      return `http://localhost:3001${imagePath}`
    }
  } catch (e) {
    console.error('解析图片URL失败:', e)
  }
  
  return defaultProduct
}

// 处理图片加载错误
const handleImageError = (e) => {
    console.error('图片加载失败:', e.target.src);
    e.target.src = defaultProduct;
}

// 添加调试日志
watch([searchQuery, statusFilter, timeFilter], ([newSearch, newStatus, newTime]) => {
  console.log('筛选条件变化:', {
    searchQuery: newSearch,
    statusFilter: newStatus,
    timeFilter: newTime,
    filteredCount: filteredOrders.value.length,
    totalCount: orders.value.length,
    // 只显示订单号相关信息
    sampleOrder: orders.value[0] ? {
      order_id: orders.value[0].order_id,
      order_status: orders.value[0].order_status
    } : null
  })
})

onMounted(() => {
    fetchOrders()
})
</script>

<template>
    <div class="orders-page">
        <div class="page-header">
            <h2>订单管理</h2>
            <button 
                class="refresh-btn" 
                @click="fetchOrders"
                :disabled="loading"
            >
                <i class="fa-solid fa-rotate" :class="{ 'fa-spin': loading }"></i>
                {{ loading ? '加载中...' : '刷新' }}
            </button>
        </div>

        <!-- 添加搜索和筛选区域 -->
        <div class="filter-section">
          <div class="search-box">
            <i class="fa-solid fa-search"></i>
            <input
              type="text"
              v-model="searchQuery"
              placeholder="请输入订单号搜索..."
            />
          </div>
          
          <div class="filter-group">
            <select v-model="statusFilter">
              <option 
                v-for="option in statusOptions" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </option>
            </select>

            <select v-model="timeFilter">
              <option 
                v-for="option in timeOptions" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </option>
            </select>

            <button class="reset-btn" @click="resetFilters">
              <i class="fa-solid fa-rotate-left"></i>
              重置
            </button>
          </div>
        </div>

        <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
        </div>

        <div class="orders-table">
            <table>
                <thead>
                    <tr>
                        <th>订单编号</th>
                        <th>商品信息</th>
                        <th>订单金额</th>
                        <th>收货信息</th>
                        <th>订单状态</th>
                        <th>下单时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td colspan="7" class="loading-cell">
                            <i class="fa-solid fa-spinner fa-spin"></i>
                            加载中...
                        </td>
                    </tr>
                    <tr v-else-if="filteredOrders.length === 0">
                        <td colspan="7" class="empty-cell">
                            {{ searchQuery || statusFilter !== 'all' || timeFilter !== 'all' 
                              ? '没有找到匹配的订单' 
                              : '暂无订单数据' 
                            }}
                        </td>
                    </tr>
                    <template v-else>
                        <tr v-for="order in filteredOrders" :key="order.order_id">
                            <td>{{ order.order_id }}</td>
                           
                            <td class="product-info">
                            
                                <img 
                                    :src="getImageUrl(order.product_images)"
                                    :alt="order.product_name"
                                    class="product-image"
                                    @error="handleImageError"
                                >
                                <div class="product-details">
                                    <div class="product-name">{{ order.product_name }}</div>
                                    <div class="product-price">{{ order.total_price?order.total_price:0 }}</div>
                                    <div class="quantity">x{{ order.quantity || 1 }}</div>
                                </div>
                            </td>
                            <td>{{ order.total_price?order.total_price:0 }}</td>
                            <td class="address-info">
                                <div>{{ order.shipping_address }}</div>
                            </td>
                            <td>
                                <span 
                                    class="status-tag"
                                    :style="{ 
                                        backgroundColor: ORDER_STATUS[order.order_status]?.color + '1A',
                                        color: ORDER_STATUS[order.order_status]?.color
                                    }"
                                >
                                    {{ getStatusText(order.order_status) }}
                                </span>
                            </td>
                            <td>{{ formatDate(order.created_at) }}</td>
                            <td class="actions">
                                <div class="status-actions" v-if="order.order_status !== 'delivered' && order.order_status !== 'cancelled'">
                                    <button 
                                        v-if="order.order_status === 'pending'"
                                        class="action-btn confirm"
                                        @click="updateOrderStatus(order.order_id, 'confirmed')"
                                    >
                                        确认
                                    </button>
                                    <button 
                                        v-if="order.order_status === 'confirmed'"
                                        class="action-btn ship"
                                        @click="updateOrderStatus(order.order_id, 'shipped')"
                                    >
                                        发货
                                    </button>
                                    <button 
                                        v-if="order.order_status === 'shipped'"
                                        class="action-btn complete"
                                        @click="updateOrderStatus(order.order_id, 'delivered')"
                                    >
                                        完成
                                    </button>
                                </div>
                                <button 
                                    v-if="order.order_status === 'pending'"
                                    class="action-btn cancel"
                                    @click="updateOrderStatus(order.order_id, 'cancelled')"
                                >
                                    取消
                                </button>
                                <button 
                                    class="action-btn delete"
                                    @click="deleteOrder(order.order_id)"
                                >
                                    <i class="fa-solid fa-trash"></i>
                                    删除
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>
</template>

<style scoped>
.orders-page {
    padding: 24px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.refresh-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    background: white;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
}

.refresh-btn:hover:not(:disabled) {
    border-color: #1890ff;
    color: #1890ff;
}

.orders-table {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: auto;
    min-height: 400px;
}

table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

th, td {
    padding: 16px;
    text-align: left;
    border-bottom: 1px solid #e5e7eb;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

th:nth-child(1), td:nth-child(1) { width: 100px; }
th:nth-child(2), td:nth-child(2) { width: 200px; }
th:nth-child(3), td:nth-child(3) { width: 100px; }
th:nth-child(4), td:nth-child(4) { width: 200px; }
th:nth-child(5), td:nth-child(5) { width: 100px; }
th:nth-child(6), td:nth-child(6) { width: 150px; }
th:nth-child(7), td:nth-child(7) { width: 150px; }

.product-info {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}

.product-image {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    background: #f5f5f5;
    flex-shrink: 0;
    background-image: url('/images/default-product.png');
    background-size: cover;
    background-position: center;
}

.product-details {
    min-width: 0;
    flex: 1;
}

.product-name {
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.product-price {
    color: #ff4d4f;
}

.address-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.address {
    color: #666;
    font-size: 12px;
}

.status-tag {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
}

.actions {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 8px;
    height: 100%;
}

.action-btn {
    padding: 4px 8px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s;
}

.action-btn.confirm {
    background: #e6f7ff;
    color: #1890ff;
}

.action-btn.cancel {
    background: #fff2f0;
    color: #ff4d4f;
}

.action-btn.ship {
    background: #e6f7ff;
    color: #1890ff;
}

.action-btn.complete {
    background: #f6ffed;
    color: #52c41a;
}

.action-btn.delete {
    background: #fff2f0;
    color: #ff4d4f;
}

.action-btn.delete:hover {
    background: #ffd4d4;
}

.loading-cell,
.empty-cell {
    text-align: center;
    height: 200px;
    line-height: 200px;
    color: #6b7280;
}

.error-message {
    margin-bottom: 16px;
    padding: 12px;
    background: #fff2f0;
    border: 1px solid #ffccc7;
    border-radius: 6px;
    color: #ff4d4f;
}

.loading-placeholder {
    background: #f3f4f6;
    border-radius: 4px;
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0% { opacity: 0.6; }
    50% { opacity: 0.8; }
    100% { opacity: 0.6; }
}

.product-image {
    transition: opacity 0.3s;
}

.product-image[src=''] {
    opacity: 0;
}

.product-image[src]:not([src='']) {
    opacity: 1;
}

tbody tr:hover {
    background-color: #f9fafb;
}

@media (max-width: 1200px) {
    .orders-table {
        overflow-x: auto;
    }
    
    table {
        min-width: 1000px;
    }
}

/* 复用之前的搜索和筛选样式 */
.filter-section {
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-box {
  flex: 1;
  min-width: 200px;
  position: relative;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  font-size: 14px;
  transition: all 0.3s;
}

.search-box input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  outline: none;
}

.filter-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  cursor: pointer;
  min-width: 120px;
  font-size: 14px;
  transition: all 0.3s;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236B7280'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 8px center;
  background-size: 16px;
  padding-right: 32px;
}

.filter-group select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  outline: none;
}

.reset-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.reset-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
  background: #e6f7ff;
}

.reset-btn i {
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-group {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .filter-group select,
  .reset-btn {
    flex: 1;
    min-width: 0;
  }
}
</style> 